import urllib.request as ur
import urllib.parse as up
import json

while True:
    word = input('请输入要翻译的中文：')
    # 构造request查询条件
    data = {'kw': word}
    # 将查询条件url编码
    data_url = up.urlencode(data)
    request = ur.Request(url='https://fanyi.baidu.com/sug', data=data_url.encode('utf-8'))
    # 获取返回Json对象
    response = ur.urlopen(request).read()
    # 反序列化Json对象
    result = json.loads(response)
    # 判断数据正确返回
    if len(result['data']) > 0:
        # 正确返回，输出结果
        translate = result['data'][0]['v']
        print('翻译结果：', translate)
    else:
        # 错误，提示用户
        print('翻译失败。')
